package base

import (
	"crypto/rand"
	"errors"
	"fmt"
	"math/big"

	"gorm.io/gorm"

	"gitcode.com/G-YT/baoyou/server/model/common/response"
	"gitcode.com/G-YT/baoyou/server/utils/sms"
	"github.com/gin-gonic/gin"
)

type BaseApi struct {
}

// SendCaptcha 获取短信验证码
func (b *BaseApi) SendCaptcha(c *gin.Context) {
	type req struct {
		Phone string `json:"phone" form:"phone"`
	}
	var r req
	if err := c.ShouldBindJSON(&r); err != nil || r.Phone == "" {
		response.FailWithMessage("手机号不能为空", c)
		return
	}
	code := generateCode()
	if err := sms.SendSMS(r.Phone, code); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	response.OkWithMessage("发送成功", c)
}

// SendCaptchaB1 获取短信验证码B1
func (b *BaseApi) SendCaptchaB1(c *gin.Context) {
	type req struct {
		Phone string `json:"phone" form:"phone"`
	}
	var r req
	if err := c.ShouldBindJSON(&r); err != nil || r.Phone == "" {
		response.FailWithMessage("手机号不能为空", c)
		return
	}
	info, loginErr := HealthManagerService.FindManagerByWhere(map[string]interface{}{"phone": r.Phone}, "*")
	if errors.Is(loginErr, gorm.ErrRecordNotFound) {
		code := generateCode()
		if err := sms.SendSMS(r.Phone, code); err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
		response.OkWithMessage("发送成功", c)
		return
	}
	if loginErr != nil {
		response.FailWithMessage(loginErr.Error(), c)
		return
	}
	switch info.RegisterStatus {
	case 1:
		code := generateCode()
		if err := sms.SendSMS(r.Phone, code); err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
		response.OkWithMessage("发送成功", c)
	case 0:
		response.FailWithMessage("注册审核中,暂不能获取验证码", c)
	case 2:
		response.FailWithMessage("注册申请被驳回，暂不能获取验证码", c)
	default:
		response.FailWithMessage("注册状态异常，暂不能获取验证码", c)
	}
}

func generateCode() string {
	n, _ := rand.Int(rand.Reader, big.NewInt(1000000))
	return fmt.Sprintf("%06d", n.Int64())
}
